import json

import numpy as np
import cv2


def show_projection_image(image, projection_vertex, vertex_view_size=None):
    draw = image.copy()
    projection_vertex_trans = projection_vertex.copy()
    if vertex_view_size is not None:
        h, w = image.shape[:2]
        ar_h, ar_w = vertex_view_size
        projection_vertex_trans[:, 0] /= ar_w
        projection_vertex_trans[:, 1] /= ar_h
        projection_vertex_trans[:, 0] *= w
        projection_vertex_trans[:, 1] *= h

    for x, y in projection_vertex_trans.astype(int):
        cv2.circle(draw, (x, y), radius=1, color=(0, 255, 0), thickness=2)

    cv2.imshow("image", draw)
    cv2.waitKey(0)


def get_rotation_matrix(rotation_angle, center):
    rotation_angle_radians = np.radians(rotation_angle)
    cos_angle = np.cos(rotation_angle_radians)
    sin_angle = np.sin(rotation_angle_radians)

    affine_matrix = np.array([
        [cos_angle, -sin_angle, center[0] * (1 - cos_angle) + center[1] * sin_angle],
        [sin_angle, cos_angle, center[1] * (1 - cos_angle) - center[0] * sin_angle]
    ])

    return affine_matrix

def transform_points(points, affine_matrix):
    # 将2D点集转换为齐次坐标形式（添加一个值为1的维度）
    homogeneous_points = np.hstack((points, np.ones((points.shape[0], 1))))

    # 对齐次坐标点集应用affine矩阵
    transformed_points = np.dot(homogeneous_points, affine_matrix.T)

    # 将变换后的点集从齐次坐标转换回2D坐标
    transformed_points_2d = transformed_points[:, :2]

    return transformed_points_2d


def rotate_image(image, rotation_angle):

    # 获取图像的尺寸
    (h, w) = image.shape[:2]

    # 计算旋转的中心点
    center = (w // 2, h // 2)

    # 获取旋转矩阵
    affine_matrix = get_rotation_matrix(rotation_angle, center)

    # 应用变换矩阵
    rotated_image = cv2.warpAffine(image, affine_matrix, (w, h))

    return rotated_image, affine_matrix


if __name__ == '__main__':
    with open("data/data.json", "r") as f:
        data = json.load(f)

    # 解析ARSCNView视图的数据
    # image = cv2.imread("data/datad.jpg")
    # arscn_projection_vertex = np.asarray(data['projected'])
    # show_projection_image(image, arscn_projection_vertex, vertex_view_size=(844, 390))


    # 解析原始相机流视图的数据
    image = cv2.imread("data/data.jpg")
    height, width = image.shape[:2]
    projection_vertex = np.asarray(data['capProjected'])
    projection_vertex[:, 0] = width - projection_vertex[:, 0]

    rotated_image, affine_matrix = rotate_image(image, 90)
    rotated_projection_vertex = transform_points(projection_vertex, affine_matrix)
    show_projection_image(rotated_image, rotated_projection_vertex)
